import React, { useEffect, useState } from 'react';

const HeartbeatComponent = () => {
  const [isUserActive, setIsUserActive] = useState(true);

  useEffect(() => {
    let idleTimeout;
    let heartbeatInterval;
    let lastMouseActivityTime = new Date().getTime();

    const handleUserActivity = () => {
      const currentTime = new Date().getTime();
      localStorage.setItem('heartbeat', currentTime.toString());
      setIsUserActive(true);

      // 记录最后一次鼠标活动时间
      lastMouseActivityTime = currentTime;

      // 重置定时器
      clearTimeout(idleTimeout);
      idleTimeout = setTimeout(() => {
        setIsUserActive(false);
        console.log("用户不活跃")
      }, 20000); // 一分钟未活动时认为用户不活跃

      // 每隔30秒写入当前时间到缓存
      heartbeatInterval = setInterval(() => {
        localStorage.setItem('heartbeat', new Date().getTime().toString());
        console.log("写入缓存18行",new Date().toTimeString())
      }, 5000);
    };

    const checkHeartbeat = () => {
      const lastHeartbeat = localStorage.getItem('heartbeat');
      if (lastHeartbeat) {
        const currentTime = new Date().getTime();
        const timeDiff = currentTime - parseInt(lastHeartbeat, 10);

        if (timeDiff > 200000 && isUserActive) {
          // 用户超过一个小时未活动，给出提示
          console.log('用户超过一个小时未活动！');
        }
      }
    };

    // 添加事件监听器
    document.addEventListener('mousemove', handleUserActivity);

    // 初始化定时器
    idleTimeout = setTimeout(() => {
      setIsUserActive(false);
      console.log("用户不活跃")
    }, 20000);

    // 初始化心跳定时器
    heartbeatInterval = setInterval(() => {
      localStorage.setItem('heartbeat', new Date().getTime().toString());
      console.log("写入缓存18行",new Date().toTimeString())
    }, 5000);

    // 检查心跳
    const checkInterval = setInterval(checkHeartbeat, 1000);

    // 在组件卸载时清理定时器和事件监听器
    return () => {
      document.removeEventListener('mousemove', handleUserActivity);
      clearTimeout(idleTimeout);
      clearInterval(heartbeatInterval);
      clearInterval(checkInterval);
    };
  }, [isUserActive]);

  return (
    <div>
      {isUserActive ? (
        <p>User is active!</p>
      ) : (
        <p>User is inactive for more than 1 minute.</p>
      )}
    </div>
  );
};

export default HeartbeatComponent;
